//
//  CourseDetailViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/15.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "CourseDetailViewController.h"
#import "INtroduceCourseTableViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "CourseDetailHeadView.h"
#import "AllHeader.h"
#import "CourseViewController.h"
#import "CourseDetailModel.h"
/// 微信分享
#import "ShareViewController.h"
#import <UIImageView+WebCache.h>

//  支付动画
#import "PayAnimationViewController.h"
#import "PayVC.h"

// http://arts1hangzhou.oss-cn-hangzhou.aliyuncs.com/iPad%20Pro%20-%20Reveal.mp4?OSSAccessKeyId=btSqdMIkhrmma4ZQ&amp;Expires=1441884417&amp;Signature=rh%2BLdxOZjbXtkgqgW5LsbuGmYmU%3D
// #define  cURL @"http://arts1hangzhou.oss-cn-hangzhou.aliyuncs.com/iPad%20Pro%20-%20Reveal.mp4"

// 课程详情
#define  cDURL @"http://arts1.dlab.com.cn/app/courseinfo"
//#define  cDURL @"http://arts1.cn/app/courseinfo"

// 点赞
#define goodURL @"http://arts1.dlab.com.cn/app/zan"
//#define goodURL @"http://arts1.cn/app/zan"

 // 视频收藏
//#define  storeURL @"http://arts1.dlab.com.cn/app/collectvideo"
#define  storeURL @"http://arts1.cn/app/collectvideo"


#define  oderURL @"http://www.arts1.cn/app/order"

@interface CourseDetailViewController ()

// 自定义navigation视图
@property (nonatomic, strong) CourseDetailHeadView *navigationview;

// 视频播放器
@property (nonatomic, strong) MPMoviePlayerController *playController;

// 课程介绍
@property (nonatomic, strong) UIButton *leftBTN;

// 视频详情
@property (nonatomic, strong) UIButton *rightBTN;

// tabbar上的遮盖视图
@property (nonatomic, strong) UIView *bottomView;

// 视图底部的tabbar按钮
@property (nonatomic, strong) UIButton *tabBarBTN;

// 课程介绍页面
@property (nonatomic, strong) INtroduceCourseTableViewController *courseIVC;

// 分享选项页面
@property (nonatomic, strong) ShareViewController *shareVC;

// model类
@property (nonatomic, strong) CourseDetailModel *course;

// 视频播放 url
@property (nonatomic, strong) NSString *url;


// 生成渐变层
@property (strong, nonatomic) CAGradientLayer *gradientLayer;

// 支付动画
@property (nonatomic, strong) PayAnimationViewController *payAnimationVC;

@property (nonatomic, strong) UIButton *removePayViewButton;

@property (nonatomic, strong) UIButton *payButton;

@property (nonatomic, strong) NSDictionary *oderDic;





@end

@implementation CourseDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    [self requestData];
    
    [self createNavigationBar];
    [self createPlayView];
    [self createCourseIntroduceview];
    [self createButtons];
    [self createTabBarView];
    [self createShareView];
    [self requistOder];
}

#pragma mark ***网络请求
// 网络请求
- (void)requestData{
        AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
        manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
        manage.responseSerializer = [AFHTTPResponseSerializer serializer];
        
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSString *uid = userDic[@"data"][@"uid"];
    NSString *key = userDic[@"data"][@"key"];
    
    //请求参数
   NSDictionary *pardic = @{@"courseId":_model.Id,@"uid":uid,@"key":key};
    
    NSLog(@"uid === %@ ***** key %@",uid, key);
    
        [manage POST:cDURL parameters:pardic
             success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             //返回的状态
             int index = [dic[@"status"] intValue];
             if (index == 1) {
                 NSDictionary *dict = dic[@"data"];
                 _course = [[CourseDetailModel alloc] init];
                 [_course setValuesForKeysWithDictionary:dict];
             }
             
             NSLog(@"视频详情*****返回数据 ： %@", dic);
             // 判断是否有观看权限 isAllow
             dispatch_async(dispatch_get_main_queue(), ^{
                 _navigationview.course = _course;
                 _courseIVC.detail = _course;
                 if ([_course.isAllow intValue]) {
                     [self addURLToPlay];
                 } else {
                     [self addImageViewForPlayView];
                     [MBProgressHUD show:@"您还没有权限视频观看" icon:nil view:self.view];
                 }
             });
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

#pragma mark ***addURLToPlay-判断用户是否具有播放权限
/**
 *  用户具有视频播放权限之后,给视频播放器添加url
 */
- (void)addURLToPlay{
    _url = [_course.videoUrl componentsSeparatedByString:@"?"][0];
    _playController.contentURL = [NSURL URLWithString:[_url stringByAppendingString:@"?"]];
}
/**
 *  用户不具有视频播放权限之后,给视频播放器添加背景图片
 */
- (void)addImageViewForPlayView{
    _url = nil;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:_playController.view.bounds];
    [imageView setContentMode:(UIViewContentModeScaleAspectFill)];
    imageView.layer.masksToBounds = YES;
    [imageView sd_setImageWithURL:[NSURL URLWithString:_course.photo] placeholderImage:nil options:(SDWebImageRetryFailed | SDWebImageLowPriority)];
    [_playController.view addSubview:imageView];
    
}


// 自定义navigationbar
- (void)createNavigationBar{
    _navigationview = [[CourseDetailHeadView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
    _navigationview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_navigationview];
    //  给返回按钮添加点击事件
    [_navigationview.backButton addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
    //  给分享按钮添加点击事件
    [_navigationview.shareBTN addTarget:self action:@selector(shareMessage:) forControlEvents:(UIControlEventTouchUpInside)];
}

// 后退
- (void)back:(UIButton *)btn{
    self.tabBarController.tabBar.hidden = NO;
    [_playController stop];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)obtianCourseViewController{
    UITabBarController *tabVC = (UITabBarController *)self.view.window.rootViewController;
    UINavigationController *navi = (UINavigationController *)tabVC.viewControllers[0];
    CourseViewController *courseVC = (CourseViewController *)navi.viewControllers[0];
    courseVC.searchVC.view.frame = CGRectMake(0,0,SCREEN_WIDTH,64);
    courseVC.searchVC.resultView.frame =  CGRectMake(0,64,SCREEN_WIDTH,0);
}


// 创建分享选项卡
- (void)createShareView{
    _shareVC = [[ShareViewController alloc] init];
    [self.view addSubview:_shareVC.view];
    _shareVC.view.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
}


// 分享
- (void)shareMessage:(UIButton *)btn{
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _shareVC.view.frame = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark  ---  视频播放
- (void)createPlayView{
    _playController = [[MPMoviePlayerController alloc] init];
    _playController.view.frame = CGRectMake(0, _navigationview.bottom, SCREEN_WIDTH, 201 * HEIGHT);
    _playController.controlStyle = MPMovieControlStyleEmbedded;
    [self.view addSubview:_playController.view];
    [_playController prepareToPlay];
}


// 课程介绍、视屏详情
- (void)createButtons{
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, _playController.view.bottom, SCREEN_WIDTH, 40)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [UIView viewWideForShadowColor:whiteView];
   // [UIView viewShadowColor:whiteView];
    
    // 下载
    _leftBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _leftBTN.frame = CGRectMake(0, 0, whiteView.width / 2.0 - 0.5, whiteView.height);
    if (_model.iscollect) {
       [_leftBTN setTitle:@"   取消收藏" forState:(UIControlStateNormal)];
    } else {
    [_leftBTN setTitle:@"  收藏" forState:(UIControlStateNormal)];
    }
    [_leftBTN setImage:[UIImage imageNamed:@"downloadButton"] forState:(UIControlStateNormal)];
    _leftBTN.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [_leftBTN setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    [_leftBTN addTarget:self action:@selector(introduceCourse:) forControlEvents:(UIControlEventTouchUpInside)];
    [whiteView addSubview:_leftBTN];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(whiteView.width / 2.0 -0.5, 5, 1, 30)];
    line.backgroundColor = sFONTCOLOR;
    [whiteView addSubview:line];
    
    // 称赞
    _rightBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _rightBTN.frame = CGRectMake(_leftBTN.right + 1, 0, whiteView.width / 2.0 - 0.5, whiteView.height);
    [_rightBTN setTitleColor:sFONTCOLOR forState:(UIControlStateNormal)];
    [_rightBTN setTitle:@"  称赞" forState:(UIControlStateNormal)];
    _rightBTN.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [_rightBTN setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    [_rightBTN setImage:[UIImage imageNamed:@"tabGoodButton"] forState:(UIControlStateNormal)];
    [_rightBTN addTarget:self action:@selector(introduceMedia:) forControlEvents:(UIControlEventTouchUpInside)];
    [whiteView addSubview:_rightBTN];
    
    [self.view addSubview:whiteView];
}


// 下载  相应地改为   视频收藏
- (void)introduceCourse:(UIButton *)btn{
    [_leftBTN setTitleColor:lFONTCOLOR forState:(UIControlStateNormal)];
    [_rightBTN setTitleColor:sFONTCOLOR forState:(UIControlStateNormal)];
    int collect = [_model.iscollect intValue];
    if (collect) {
        [_leftBTN setTitle:@"取消收藏" forState:(UIControlStateNormal)];
    } else {
        [_leftBTN setTitle:@"收藏" forState:(UIControlStateNormal)];
    }
      [self storeCourseVideo];
}
/**
 *  视频收藏  ---  视频详情
 */
- (void)storeCourseVideo{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    //请求参数
    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"courseId":_model.Id};
    
    [manage POST:storeURL parameters:pardic
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 请求成功的时候调用这个block
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            // 请求返回的状态，当status = 1 时有数据
            NSInteger status = [dic[@"status"] integerValue];
            
            NSString *str = nil;
                switch (status) {
                    case 1:{
                        str = @"操作成功";
                        _model.iscollect = dic[@"iscollect"];
                    }
                        break;
                    case 0:
                        str = @"没有视频信息";
                        break;
                    case -1:
                        str = @"未登录";
                        break;
                    case -2:
                        str = @"用户名或密码错误";
                        break;
                    case -3:
                        str = @"参数不正确";
                        break;
                    default:
                        break;
            }
            
            NSLog(@" 视频收藏  返回数据 ： %@ ",dic);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // 请求失败的时候调用调用这个block
            NSLog(@"请求失败");
        }];


}

// 称赞
- (void)introduceMedia:(UIButton *)btn{
    [_leftBTN setTitleColor:sFONTCOLOR forState:(UIControlStateNormal)];
    [_rightBTN setTitleColor:lFONTCOLOR forState:(UIControlStateNormal)];
    [self requestGoodDataAndStatus];
}

/**
 *  视频点赞，网络请求
 */
- (void)requestGoodDataAndStatus
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *pardic = @{@"id":_model.Id,@"type":@"course"};
    
    [manage GET:goodURL parameters:pardic
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 请求成功的时候调用这个block
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            // 请求返回的状态，当status = 1 时有数据
            NSInteger status = [dic[@"status"] integerValue];
            if (status == 1) {
                //信息提示框
                [MBProgressHUD show:@"操作成功" icon:nil view:self.view];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // 请求失败的时候调用调用这个block
            NSLog(@"请求失败");
        }];
    
}

// 创建视频介绍页面
- (void)createCourseIntroduceview{
    _courseIVC = [[INtroduceCourseTableViewController alloc] init];
    _courseIVC.view.frame = CGRectMake(0 , _playController.view.bottom + 40 , SCREEN_WIDTH, SCREEN_HEIGHT - _playController.view.bottom - 89);
    _courseIVC.view.backgroundColor = kBackgroundColor;
    _courseIVC.tableView.frame = CGRectMake(0 , _playController.view.bottom + 40 , _courseIVC.view.size.width,  SCREEN_HEIGHT - _playController.view.bottom - 89);
    
    _payAnimationVC.price = _course.price;
     _payAnimationVC.courseName = _course.title;
    
    [self.view addSubview:_courseIVC.view];
    
}

//  创建tabbarview视图
- (void)createTabBarView{
    // tabbar上面的遮盖视图
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
    _bottomView.backgroundColor = lFONTCOLOR;
    
    // 播放页面底部的 “支持｜更多” 按钮
    _tabBarBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _tabBarBTN.frame = CGRectMake(SCREEN_WIDTH/2.0 - 45, 9.5, 90, 30);
    _tabBarBTN.titleLabel.font = [UIFont systemFontOfSize:16];
    _tabBarBTN.backgroundColor = lFONTCOLOR;
    _tabBarBTN.tintColor = sFONTCOLOR;
    [_tabBarBTN setTitle:@"购买" forState:(UIControlStateNormal)];
//    [_tabBarBTN addTarget:self action:@selector(tapToVIP) forControlEvents:(UIControlEventTouchUpInside)];
    [_tabBarBTN addTarget:self action:@selector(tapToPay:) forControlEvents:(UIControlEventTouchUpInside)];
    [_bottomView addSubview:_tabBarBTN];
    [self.view addSubview:_bottomView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{    
//    [_iamgeVIew removeFromSuperview];
//    [self createTabBarView];
}

/**
 *  支持 ｜ 更多  点击事件
 */
- (void)tapToVIP{
    // 关闭视频
    [_playController stop];
    
    /**
     添加支付动画    加载会员介绍页面
     */
    _payAnimationVC = [[PayAnimationViewController alloc] init];
    _payAnimationVC.price = _course.price;
    _payAnimationVC.courseName = _course.title;
    [self.view addSubview:_payAnimationVC.view];
    
    _payButton = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
    _payButton.frame = CGRectMake(_payAnimationVC.backgroundView.size.width - 15 - 65 + 25, SCREEN_HEIGHT / 2 - 210 / 2 - 50 + _payAnimationVC.backgroundView.size.height - 17 - 37, 65, 37);;
    _payButton.layer.cornerRadius = 5;
    _payButton.layer.masksToBounds = YES;
    _payButton.alpha = 0;
    _payButton.backgroundColor = kCustomColor(245, 165, 35, 1);
    [_payButton setTitle:@"购买" forState:(UIControlStateNormal)];
    _payButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [_payButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_payButton addTarget:self action:@selector(tapToVIP:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_payButton];
    
    [UIView animateWithDuration:0.1 delay:2.3 options:(UIViewAnimationOptionCurveEaseIn) animations:^{
        _payButton.alpha = 1;
    } completion:nil];
    
    _removePayViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _removePayViewButton.frame = CGRectMake(SCREEN_WIDTH / 2.0 - 20, SCREEN_HEIGHT - 100 *HEIGHT, 40, 40);
    _removePayViewButton.alpha = 0.3;
    [_removePayViewButton setBackgroundImage:[UIImage imageNamed:@"cancelcon"] forState:(UIControlStateNormal)];
    [_removePayViewButton addTarget:self action:@selector(removePayAnimationView) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_removePayViewButton];
    

}

/**
 *  点击购买  ------   进入支付页面
 */

- (void)tapToPay:(UIButton *)tapSet
{
    PayVC *payVC = [[PayVC alloc] init];
    payVC.oderDictionary = _oderDic;
    payVC.course = _course;
    [self.navigationController pushViewController:payVC animated:YES];
    [self removePayAnimationView];
    
    NSLog(@"==== 进入支付页面 ====");
}

//取消当前页面
- (void)removePayAnimationView
{
    [_payAnimationVC.view removeFromSuperview];
    [_payButton removeFromSuperview];
    [_removePayViewButton removeFromSuperview];
}



/**
 *  创建订单
 */
- (void)requistOder{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    //请求参数
    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"id":_model.Id,@"type":@"course"};
//    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"courseId":_model.Id};
    
    [manage POST:oderURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             // 请求返回的状态，当status = 1 时有数据
             NSInteger status = [dic[@"status"] integerValue];
             
             if (status == 1) {
                 _oderDic = dic;
             }
             
             NSLog(@" 创建订单  返回数据 ： %@ ",dic);
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
    
    
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
